import 'dart:convert';
import 'package:decimal/decimal.dart';
import 'package:ecy_app_flutter/routes/consignment/model/ShopVo.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:intl/intl.dart';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:ecy_app_flutter/constant/constant.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import '../../../EcyRouter.dart';
import '../../../constant/EcyEventConsnt.dart';
import '../../../ecycommon/EcyAPI.dart';
import '../../../ecycommon/EcyRequestBaseManager.dart';
import '../../../ecycommon/utils/ClipboardUtil.dart';
import '../../../ecycommon/utils/EcyAlipayUtil.dart';
import '../../../ecycommon/utils/EcyQQUtil.dart';
import '../../../ecycommon/utils/EcyStorage.dart';
import '../../../ecycommon/utils/EcyWxUtil.dart';
import '../../../model/EcyApiCommonResponse.dart';
import '../../../model/EcyLocationModel.dart';
import '../../login/common/DateUtil.dart';
import '../model/Logistics.dart';
import '../model/UserGroupBuyItemVo.dart';
import '../model/order/UserAddress.dart';
import '../model/order/UserOrder.dart';
import '../model/order/UserOrderDetail.dart';
import '../model/order/UserOrderItem.dart';
import '../model/order/UserOrderPay.dart';

class EcyOrderInfoPage extends StatefulWidget {
  final String orderId;
  Function? onCallback;

  EcyOrderInfoPage(this.orderId, [this.onCallback]);

  @override
  _EcyOrderInfoPageState createState() => _EcyOrderInfoPageState(this.orderId, this.onCallback);
}

class _EcyOrderInfoPageState extends State<EcyOrderInfoPage> {
  final String orderId;
  Function? _onCallback;

  _EcyOrderInfoPageState(this.orderId, [this._onCallback]);

  UserOrderDetail _userOrderDetail = UserOrderDetail();
  UserOrder _order = UserOrder();
  UserOrderPay _orderPay = UserOrderPay();
  List<UserOrderItem> _orderItems = [];
  UserAddress _userAddress = UserAddress();
  final Map<String, List<UserGroupBuyItemVo>> _groupBuyIdMap = {};
  ShopVo _shopVo = ShopVo();

  double _totalPrice = 0.00;
  final _orderStatusMap = {
    0: "待付款",
    1: "买家已付款",
    2: "拼团中",
    3: "待发货",
    4: "已发货",
    5: "已完成",
    6: "已取消",
    7: "交易关闭",
    8: "拼团失败",
    9: "等待商家处理",
    10: "已退款",
    11: "待核销"
  };
  final _orderTypeMap = {
    "0": "普通商品",
    "1": "普通拼团商品",
    "2": "盲抽商品",
    "3": "端盒商品",
    "4": "盲盒拼团商品",
  };
  final logisticsStatusMap = {
    "WAIT_ACCEPT": "待揽收",
    "ACCEPT": "已揽收",
    "TRANSPORT": "运输中",
    "DELIVERING": "派件中",
    "AGENT_SIGN": "已代签收",
    "SIGN": "已签收",
    "FAILED": "包裹异常",
  };

  @override
  void initState() {
    super.initState();
    requestData();
  }

  @override
  void requestData() async {
    if (orderId == null) {
      return;
    }
    var response = await EcyRequestbasemanager()
        .get("/app/api/app/order/query/orderInfo/$orderId", {});
    if (response != null) {
      EcyApiCommonResponse commonRes =
          EcyApiCommonResponse.fromJson(response, (response) => json);
      if (commonRes.code == 0 || commonRes.code == 200) {
        UserOrderDetail userOrderDetail =
            UserOrderDetail.fromJson(response["data"]);
        setState(() {
          _userOrderDetail = userOrderDetail;
          _order = _userOrderDetail.order ?? UserOrder();
          _orderPay = _userOrderDetail.orderPay ?? UserOrderPay();
          _orderItems = _userOrderDetail.orderItems ?? [];
          _userAddress = _userOrderDetail.userAddress ?? UserAddress();
          _shopVo = _userOrderDetail.shopVo ?? ShopVo();

          _totalPrice = _orderItems
              .map((e) => (e.commoditySkuTotalPrice ?? 0.00) as double)
              .reduce((value1, value2) => value1 + value2);

          Map<String, dynamic> groupBuyIdMap =
              (_userOrderDetail.groupBuyIdMap ?? {}) as Map<String, dynamic>;
          for (var entry in groupBuyIdMap.entries) {
            List<dynamic> list = (entry.value ?? []) as List<dynamic>;
            List<UserGroupBuyItemVo> list1 = list
                .map((e) =>
                    UserGroupBuyItemVo.fromJson(e as Map<String, dynamic>))
                .toList();
            _groupBuyIdMap[entry.key] = list1;
          }
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: const BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
          colors: [
            Color(0xFFFFF0F5), // 顶部浅粉色
            Color(0xFFF5F5F5), // 底部白色
          ],
          stops: [0.0, 0.3], // 渐变在30%处完成
        ),
      ),
      child: Scaffold(
        backgroundColor: Colors.transparent,
        appBar: AppBar(
            title: Text('订单详情',
                style: TextStyle(
                    fontFamily: "PingFang SC",
                    fontWeight: FontWeight.w700,
                    fontSize: 16.sp,
                    color: const Color(0xFF262626))),
            centerTitle: true,
            backgroundColor: Colors.transparent,
            leadingWidth: 50.w,
            scrolledUnderElevation: 0,
            leading: GestureDetector(
              behavior: HitTestBehavior.translucent,
              onTap: () {
                EcyRouter.pop(context, "");
              },
              child: Align(
                alignment: Alignment.centerRight,
                child: Image.asset(
                  "assets/images/ic_back.png",
                  width: 30.w,
                ),
              ),
            )),
        body: SingleChildScrollView(
          child: Padding(
            padding: const EdgeInsets.all(8),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    const Padding(padding: EdgeInsets.only(left: 10)),
                    SizedBox(
                      child:
                          Image.asset("assets/images/ic_send.png", width: 30.w),
                    ),
                    const Padding(padding: EdgeInsets.only(right: 5)),
                    SizedBox(
                      child: Text(
                          _order.shippingMethod == 1 && _order.orderStatus == 5
                              ? "已核销"
                              : _orderStatusMap[_order.orderStatus] ??
                                  "订单状态待更新",
                          style: TextStyle(
                              fontFamily: "PingFang SC",
                              fontWeight: FontWeight.w700,
                              fontSize: 24.sp,
                              color: const Color(0xFF000000))),
                    )
                  ],
                ),
                const Padding(
                  padding: EdgeInsets.only(bottom: 6),
                ),
                if (_order.shippingMethod == 1 &&
                    ([1, 3, 4, 5, 11].contains(_order.orderStatus)))
                  Padding(
                    padding: const EdgeInsets.only(bottom: 3),
                    child: Card(
                        color: Colors.white,
                        elevation: 0,
                        child: SizedBox(
                          width: MediaQuery.of(context).size.width,
                          child: Padding(
                              padding:
                                  const EdgeInsets.only(top: 12, bottom: 12),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.center,
                                children: [
                                  Text("自提核销码",
                                      style: TextStyle(
                                          fontFamily: "PingFang SC",
                                          fontWeight: FontWeight.w700,
                                          fontSize: 16.sp,
                                          color: const Color(0xFF262626))),
                                  const Padding(
                                      padding: EdgeInsets.only(bottom: 6)),
                                  Text(_order.selfPickupQrcode ?? "******",
                                      style: TextStyle(
                                          fontFamily: "PingFang SC",
                                          fontWeight: FontWeight.w500,
                                          fontSize: 38.sp,
                                          color: const Color(0xFF262626))),
                                  const Padding(
                                      padding: EdgeInsets.only(bottom: 6)),
                                  Text(
                                    '请凭核销码前往自提点提货',
                                    style: TextStyle(
                                        fontFamily: "PingFang SC",
                                        fontWeight: FontWeight.w500,
                                        fontSize: 16.sp,
                                        color: const Color(0xFFEA4B9B)),
                                  ),
                                ],
                              )),
                        )),
                  ),
                if (_order.shippingMethod == 1)
                  Padding(
                    padding: const EdgeInsets.only(bottom: 3),
                    child: Card(
                        color: Colors.white,
                        elevation: 0,
                        child: Padding(
                            padding: const EdgeInsets.only(top: 10, bottom: 10),
                            child: Row(
                              children: [
                                Expanded(
                                    flex: 1,
                                    child: Image.asset(
                                      "assets/images/ic_order_location.png",
                                      height: 26,
                                    )),
                                Expanded(
                                    flex: 7,
                                    child: Container(
                                      padding:
                                          const EdgeInsets.fromLTRB(0, 5, 5, 5),
                                      child: Column(
                                        crossAxisAlignment:
                                            CrossAxisAlignment.start,
                                        children: [
                                          Row(
                                            mainAxisAlignment:
                                                MainAxisAlignment.start,
                                            children: [
                                              Text('自提点',
                                                  style: TextStyle(
                                                      fontFamily: "PingFang SC",
                                                      fontWeight:
                                                          FontWeight.w700,
                                                      fontSize: 16.sp,
                                                      color: const Color(
                                                          0xFF262626)),
                                                  maxLines: 1,
                                                  overflow:
                                                      TextOverflow.ellipsis),
                                            ],
                                          ),
                                          const Padding(
                                              padding:
                                                  EdgeInsets.only(bottom: 3)),
                                          Text(
                                            _shopVo.name ?? "",
                                            style: TextStyle(
                                                fontFamily: "PingFang SC",
                                                fontWeight: FontWeight.w400,
                                                fontSize: 14.sp,
                                                color: const Color(0xFF8C8C8C)),
                                          ),
                                          const Padding(
                                              padding:
                                                  EdgeInsets.only(bottom: 3)),
                                          Text(
                                            '${_shopVo.provinceName ?? ""}${_shopVo.cityName ?? ""}${_shopVo.areaName ?? ""}${_shopVo.address ?? ""}',
                                            style: TextStyle(
                                                fontFamily: "PingFang SC",
                                                fontWeight: FontWeight.w400,
                                                fontSize: 14.sp,
                                                color: const Color(0xFF8C8C8C)),
                                          ),
                                          const Padding(
                                              padding:
                                                  EdgeInsets.only(bottom: 3)),
                                          Text(
                                              '营业时间：周一至周日 ${_shopVo.businessHoursStart?.substring(0, 5) ?? ""}~${_shopVo.businessHoursEnd?.substring(0, 5) ?? ""}',
                                              style: TextStyle(
                                                  fontFamily: "PingFang SC",
                                                  fontWeight: FontWeight.w400,
                                                  fontSize: 14.sp,
                                                  color:
                                                      const Color(0xFF8C8C8C)),
                                              maxLines: 2,
                                              overflow: TextOverflow.ellipsis),
                                        ],
                                      ),
                                    )),
                              ],
                            ))),
                  ),
                if (_order.shippingMethod != 1)
                  Padding(
                    padding: const EdgeInsets.only(bottom: 3),
                    child: Card(
                        color: Colors.white,
                        elevation: 0,
                        child: Padding(
                            padding: const EdgeInsets.only(top: 10, bottom: 10),
                            child: Row(
                              children: [
                                Expanded(
                                    flex: 1,
                                    child: Image.asset(
                                      "assets/images/ic_order_location.png",
                                      height: 26,
                                    )),
                                Expanded(
                                    flex: 7,
                                    child: Container(
                                      padding:
                                          const EdgeInsets.fromLTRB(0, 5, 5, 5),
                                      child: Column(
                                        crossAxisAlignment:
                                            CrossAxisAlignment.start,
                                        children: [
                                          Row(
                                            mainAxisAlignment:
                                                MainAxisAlignment.start,
                                            children: [
                                              Text(
                                                  '${_userAddress.contact ?? "买家信息待更新"}  ${_userAddress.phone ?? ""}',
                                                  style: TextStyle(
                                                      fontFamily: "PingFang SC",
                                                      fontWeight:
                                                          FontWeight.w700,
                                                      fontSize: 16.sp,
                                                      color: const Color(
                                                          0xFF262626)),
                                                  maxLines: 1,
                                                  overflow:
                                                      TextOverflow.ellipsis),
                                              const Padding(
                                                  padding: EdgeInsets.only(
                                                      right: 10)),
                                              _userAddress.addressDefault ==
                                                          null ||
                                                      _userAddress
                                                              .addressDefault ==
                                                          0
                                                  ? const Text("")
                                                  : DecoratedBox(
                                                      decoration: BoxDecoration(
                                                        borderRadius:
                                                            BorderRadius
                                                                .circular(50.0),
                                                        border: Border.all(
                                                          color: const Color(
                                                              0xFFEA4B9B),
                                                          width: 1.0,
                                                        ),
                                                      ),
                                                      child: Padding(
                                                        padding:
                                                            const EdgeInsets
                                                                .symmetric(
                                                                horizontal: 7,
                                                                vertical: 1),
                                                        child: Text(
                                                          "默认",
                                                          style: TextStyle(
                                                              fontFamily:
                                                                  "PingFang SC",
                                                              fontWeight:
                                                                  FontWeight
                                                                      .w700,
                                                              fontSize: 10.sp,
                                                              color: const Color(
                                                                  0xFFEA4B9B)),
                                                        ),
                                                      )),
                                            ],
                                          ),
                                          const Padding(
                                              padding:
                                                  EdgeInsets.only(bottom: 3)),
                                          Text(
                                              '${_userAddress.address ?? "地址待更新"} ${_userAddress.detail ?? ""}',
                                              style: TextStyle(
                                                  fontFamily: "PingFang SC",
                                                  fontWeight: FontWeight.w400,
                                                  fontSize: 14.sp,
                                                  color:
                                                      const Color(0xFF8C8C8C)),
                                              maxLines: 2,
                                              overflow: TextOverflow.ellipsis),
                                        ],
                                      ),
                                    )),
                              ],
                            ))),
                  ),
                // 商品列表
                Card(
                  color: Colors.white,
                  elevation: 0,
                  child: Padding(
                    padding: EdgeInsets.all(15.w),
                    child: Column(
                      children: [
                        ..._buildSkuList(),
                        _buildPriceRow("商品总价", "￥$_totalPrice"),
                        SizedBox(height: 8.h),
                        _buildPriceRow("运费", "￥${_order.postage ?? 0.00}"),
                        SizedBox(height: 8.h),
                        _buildPriceRow("合计", "￥${_orderPay.payAmount ?? 0.00}"),
                      ],
                    ),
                  ),
                ),
                const Padding(padding: EdgeInsets.only(bottom: 3)),
                // 订单信息
                Card(
                  color: Colors.white,
                  elevation: 0,
                  child: Padding(
                    padding: EdgeInsets.all(15.w),
                    child: Column(
                      children: [
                        _buildOrderInfoRow(
                            "订单编号", _order.orderCode ?? "", true),
                        SizedBox(height: 12.h),
                        _buildOrderInfoRow(
                            "下单时间", _formatDateTime(_order.orderTime), false),
                        if (_orderPay.payTime != null) SizedBox(height: 12.h),
                        if (_orderPay.payTime != null)
                          _buildOrderInfoRow("付款时间",
                              _formatDateTime(_orderPay.payTime), false),
                        SizedBox(height: 12.h),
                        _buildOrderInfoRow(
                            "支付方式",
                            (_orderPay.payChannel ?? _order.payChannel) == 0
                                ? "微信支付"
                                : "支付宝支付",
                            false),
                        SizedBox(height: 12.h),
                        _buildOrderInfoRow("订单类型",
                            _orderTypeMap[_order.orderType] ?? "普通商品", false),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
        bottomNavigationBar: _buildBottomButtons(),
      ),
    );
  }

  List<Widget> _buildSkuList() {
    if ((_order.orderType == "1" || _order.orderType == "4") &&
        _order.orderStatus != 0) {
      List<Widget> widgetList = [];
      for (var entry in _groupBuyIdMap.entries) {
        List<UserGroupBuyItemVo> groupItems = entry.value;
        var columnWidgets =
            groupItems.where((e) => e.orderItemId != null).map((groupItem) {
          var orderItem = _orderItems.firstWhere(
              (e) => e.id == groupItem.orderItemId,
              orElse: () => UserOrderItem());
          if (orderItem.id == null) {
            return Container();
          }
          return Column(
            children: [
              Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  SizedBox(
                    width: 80.w,
                    height: 80.w,
                    child: ClipRRect(
                      borderRadius: BorderRadius.circular(8.r),
                      child: CachedNetworkImage(
                        fit: BoxFit.cover,
                        imageUrl: '${orderItem.commoditySkuImage}',
                        placeholder: (context, url) => SizedBox(
                          width: 80.w,
                          height: 80.w,
                          child: Image.asset(
                            "assets/images/app_icon1024.png",
                            fit: BoxFit.cover,
                          ),
                        ),
                        errorWidget: (context, url, error) => SizedBox(
                          width: 80.w,
                          height: 80.w,
                          child: Image.asset(
                            "assets/images/app_icon1024.png",
                            fit: BoxFit.cover,
                          ),
                        ),
                      ),
                    ),
                  ),
                  SizedBox(width: 12.w),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Padding(padding: EdgeInsets.only(bottom: 6.h)),
                        Text(
                          orderItem.commodityName ?? "",
                          style: TextStyle(
                            fontFamily: "PingFang SC",
                            fontWeight: FontWeight.w700,
                            fontSize: 14.sp,
                            color: const Color(0xFF262626),
                          ),
                          maxLines: 2,
                          overflow: TextOverflow.ellipsis,
                        ),
                        SizedBox(height: 4.h),
                        Text(
                          orderItem.commoditySkuName ?? "",
                          style: TextStyle(
                            fontFamily: "PingFang SC",
                            fontSize: 12.sp,
                            color: const Color(0xFF8C8C8C),
                          ),
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                        ),
                        SizedBox(height: 8.h),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text(
                              "￥${orderItem.commoditySkuPrice ?? 0.00}",
                              style: TextStyle(
                                fontFamily: "PingFang SC",
                                fontSize: 14.sp,
                                fontWeight: FontWeight.w700,
                                color: const Color(0xFF262626),
                              ),
                            ),
                            Text(
                              "x1",
                              style: TextStyle(
                                fontFamily: "PingFang SC",
                                fontSize: 12.sp,
                                fontWeight: FontWeight.w500,
                                color: const Color(0xFF8C8C8C),
                              ),
                            ),
                          ],
                        ),
                      ],
                    ),
                  ),
                ],
              ),
              _getGroupBuyContainer(groupItem, groupItems),
              Divider(thickness: 0.5, height: 24.h),
            ],
          );
        }).toList();

        widgetList.addAll(columnWidgets);
      }
      return widgetList;
    }
    return _orderItems.map((orderItem) {
      return Column(
        children: [
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              SizedBox(
                width: 80.w,
                height: 80.w,
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(8.r),
                  child: CachedNetworkImage(
                    fit: BoxFit.cover,
                    imageUrl: '${orderItem.commoditySkuImage}',
                    placeholder: (context, url) => SizedBox(
                      width: 80.w,
                      height: 80.w,
                      child: Image.asset(
                        "assets/images/app_icon1024.png",
                        fit: BoxFit.cover,
                      ),
                    ),
                    errorWidget: (context, url, error) => SizedBox(
                      width: 80.w,
                      height: 80.w,
                      child: Image.asset(
                        "assets/images/app_icon1024.png",
                        fit: BoxFit.cover,
                      ),
                    ),
                  ),
                ),
              ),
              SizedBox(width: 12.w),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Padding(padding: EdgeInsets.only(bottom: 6.h)),
                    Text(
                      orderItem.commodityName ?? "",
                      style: TextStyle(
                        fontFamily: "PingFang SC",
                        fontWeight: FontWeight.w700,
                        fontSize: 14.sp,
                        color: const Color(0xFF262626),
                      ),
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                    ),
                    SizedBox(height: 4.h),
                    Text(
                      orderItem.commoditySkuName ?? "",
                      style: TextStyle(
                        fontFamily: "PingFang SC",
                        fontSize: 12.sp,
                        color: const Color(0xFF8C8C8C),
                      ),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                    SizedBox(height: 8.h),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text(
                          "￥${orderItem.commoditySkuTotalPrice ?? 0}",
                          style: TextStyle(
                            fontFamily: "PingFang SC",
                            fontSize: 14.sp,
                            fontWeight: FontWeight.w700,
                            color: const Color(0xFF262626),
                          ),
                        ),
                        Text(
                          "x${orderItem.commoditySkuNum ?? 0}",
                          style: TextStyle(
                            fontFamily: "PingFang SC",
                            fontSize: 12.sp,
                            fontWeight: FontWeight.w500,
                            color: const Color(0xFF8C8C8C),
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ],
          ),
          Divider(thickness: 0.5, height: 24.h),
        ],
      );
    }).toList();
  }

  Widget _buildPriceRow(String label, String value) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Text(
          label,
          style: TextStyle(
            fontFamily: "PingFang SC",
            fontSize: 14.sp,
            fontWeight: FontWeight.w500,
            color: const Color(0xFF262626),
          ),
        ),
        Text(
          value,
          style: TextStyle(
            fontFamily: "PingFang SC",
            fontSize: 14.sp,
            fontWeight: FontWeight.w500,
            color: const Color(0xFF262626),
          ),
        ),
      ],
    );
  }

  Widget _buildOrderInfoRow(String label, String value, bool showCopy) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Text(
          label,
          style: TextStyle(
            fontFamily: "PingFang SC",
            fontSize: 14.sp,
            fontWeight: FontWeight.w500,
            color: const Color(0xFF262626),
          ),
        ),
        Row(
          children: [
            Text(
              value,
              style: TextStyle(
                fontFamily: "PingFang SC",
                fontSize: 14.sp,
                fontWeight: FontWeight.w500,
                color: const Color(0xFF262626),
              ),
            ),
            if (showCopy)
              GestureDetector(
                onTap: () {
                  ClipboardUtil.setDataToast(value, context);
                },
                child: Padding(
                  padding: EdgeInsets.only(left: 8.w),
                  child: Text(
                    "复制",
                    style: TextStyle(
                      color: const Color(0xFFEA4B9B),
                      fontSize: 14.sp,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ),
              ),
          ],
        ),
      ],
    );
  }

  String _formatDateTime(String? dateTimeStr) {
    if (dateTimeStr == null || dateTimeStr.isEmpty) return '';
    try {
      final dateTime = DateTime.parse(dateTimeStr);
      return DateFormat('yyyy-MM-dd HH:mm:ss').format(dateTime);
    } catch (e) {
      return dateTimeStr;
    }
  }

  Widget _buildButton(String text, bool isPrimary, VoidCallback onPressed) {
    return Expanded(
      child: TextButton(
        onPressed: onPressed,
        style: TextButton.styleFrom(
          backgroundColor:
              isPrimary ? const Color(0xFFEA4B9B) : const Color(0xFFFFF0F5),
          padding: EdgeInsets.symmetric(vertical: 12.h),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(24.r),
          ),
        ),
        child: Text(
          text,
          style: TextStyle(
            color: isPrimary ? Colors.white : const Color(0xFFEA4B9B),
            fontSize: 14.sp,
            fontFamily: "PingFang SC",
            fontWeight: FontWeight.w500,
          ),
        ),
      ),
    );
  }

  Future<String> getPayInfo() async {
    var response = await EcyRequestbasemanager().post(
        EcyAPI.pay.url, {"channel": _order.payChannel, "orderId": _order.id});
    return response["data"];
  }

  pay() async {
    EasyLoading.show(status: '支付中...', dismissOnTap: false);
    try {
      EcyStorage.setString(EcyEventConst.kPayedOrderId, _order.id);
      if (_order.payChannel == 1) {
        dynamic payInfo = await getPayInfo();
        EcyAlipayUtil().startPay(payInfo, context);
      } else {
        String payInfo = await getPayInfo();
        bool wechatFlag = await EcyWxUtil().pay(json.decode(payInfo), context);
        if (!wechatFlag) {
          EasyLoading.showToast("微信支付失败，请稍后再试",
              duration: const Duration(seconds: 2));
        }
      }
    } catch (e) {
      EasyLoading.showToast("支付失败，请稍后再试", duration: const Duration(seconds: 2));
    } finally {
      EasyLoading.dismiss();
    }
  }

  /// 确认收货
  _sign() async {
    var response = await EcyRequestbasemanager()
        .post(EcyAPI.sign.url, {"orderCode": _order.orderCode});
    setState(() {
      requestData();
    });
  }

  /// 查看物流
  _logistics() async {
    List<Map<String, dynamic>> response = [];
    try {
      response = await Future.wait([
        EcyRequestbasemanager()
            .get("${EcyAPI.logistics.url}/${_order.logisticsCode}", {}),
        EcyRequestbasemanager()
            .get("${EcyAPI.address.url}/${_order.shippingId}", {}),
      ]);
    } catch (e) {
      EasyLoading.showToast("请稍后再试", duration: const Duration(seconds: 2));
    }

    if (response.isNotEmpty) {
      var logisticsResp = response[0];
      if (logisticsResp != null) {
        var logisticsCommonResponse = EcyApiCommonResponse.fromJson(
            logisticsResp, (logisticsResp) => json);
        if (logisticsCommonResponse.code == 0 ||
            logisticsCommonResponse.code == 200) {
          List<Logistics> logisticsList =
              ((response[0]["data"] ?? []) as List<dynamic>)
                  .map((e) => Logistics.fromJson(e as Map<String, dynamic>))
                  .toList();
          if (logisticsList.isEmpty) {
            EasyLoading.showToast("物流信息待更新",
                duration: const Duration(seconds: 1));
            return;
          }

          var addressResp = response[1];
          EcyLocationModel? address;
          if (addressResp != null) {
            var addressCommonResponse = EcyApiCommonResponse.fromJson(
                addressResp, (addressResp) => json);
            if (addressCommonResponse.code == 0 ||
                addressCommonResponse.code == 200) {
              address = EcyLocationModel.fromJson(response[1]["data"] ?? {});
            }
          }

          showModalBottomSheet(
            context: context,
            backgroundColor: Colors.transparent,
            isScrollControlled: true,
            builder: (context) => Container(
              height: MediaQuery.of(context).size.height * 0.7,
              decoration: const BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Container(
                    padding:
                        EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
                    decoration: BoxDecoration(
                      border: Border(
                        bottom: BorderSide(
                          color: Colors.grey.withOpacity(0.1),
                        ),
                      ),
                    ),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text(
                          "物流信息",
                          style: TextStyle(
                            fontFamily: "PingFang SC",
                            fontSize: 18.sp,
                            fontWeight: FontWeight.w600,
                            color: const Color(0xFF262626),
                          ),
                        ),
                        GestureDetector(
                          onTap: () => Navigator.pop(context),
                          child: Icon(Icons.close, size: 24.w),
                        ),
                      ],
                    ),
                  ),
                  Padding(
                    padding: EdgeInsets.only(left: 16.w, top: 8.h, bottom: 8.h),
                    child: Text(
                      "收货地址：${address?.provinceName}${address?.cityName}${address?.areaName}${address?.detail}",
                      style: TextStyle(
                        fontFamily: "PingFang SC",
                        fontWeight: FontWeight.w600,
                        fontSize: 16.sp,
                        color: const Color(0xFF262626),
                      ),
                    ),
                  ),
                  Padding(padding: EdgeInsets.only(bottom: 18.h)),
                  Expanded(
                    child: ListView.builder(
                      padding: EdgeInsets.symmetric(horizontal: 16.w),
                      itemCount: logisticsList.length,
                      itemBuilder: (context, index) {
                        final logistics = logisticsList[index];
                        final isFirst = index == 0;
                        final isLast = index == logisticsList.length - 1;

                        return Container(
                          padding: EdgeInsets.symmetric(vertical: 2.h),
                          child: Row(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              // 时间轴
                              SizedBox(
                                width: 24.w,
                                child: Column(
                                  children: [
                                    Container(
                                      width: 12.w,
                                      height: 12.w,
                                      decoration: BoxDecoration(
                                        color: isFirst
                                            ? const Color(0xFFEA4B9B)
                                            : Colors.grey.withOpacity(0.3),
                                        shape: BoxShape.circle,
                                      ),
                                    ),
                                    if (!isLast || logisticsList.length == 1)
                                      Container(
                                        width: 2.w,
                                        height: 110.h,
                                        color: Colors.grey.withOpacity(0.3),
                                      ),
                                  ],
                                ),
                              ),
                              SizedBox(width: 12.w),
                              // 物流信息
                              Expanded(
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Text(
                                      logisticsStatusMap[
                                              logistics.logisticsStatus] ??
                                          "",
                                      style: TextStyle(
                                        fontFamily: "PingFang SC",
                                        fontWeight: FontWeight.w600,
                                        fontSize: 16.sp,
                                        color: const Color(0xFF262626),
                                      ),
                                    ),
                                    SizedBox(height: 4.h),
                                    Text(
                                      logistics.logisticsDesc ?? "",
                                      style: TextStyle(
                                        fontFamily: "PingFang SC",
                                        fontWeight: FontWeight.w500,
                                        fontSize: 16.sp,
                                        color: const Color(0xFF262626),
                                      ),
                                    ),
                                    SizedBox(height: 4.h),
                                    Text(
                                      logistics.createTime
                                              ?.replaceFirst("T", "") ??
                                          "",
                                      style: TextStyle(
                                        fontFamily: "PingFang SC",
                                        fontWeight: FontWeight.w400,
                                        fontSize: 14.sp,
                                        color: const Color(0xFF8C8C8C),
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ],
                          ),
                        );
                      },
                    ),
                  ),
                ],
              ),
            ),
          );
        } else {
          EasyLoading.showToast("物流信息待更新",
              duration: const Duration(seconds: 1));
        }
      }
    }
  }

  /// 加入购物车
  _addCart() async {
    try {
      var carts = (_orderItems).map((e) {
        return {
          "commoditySkuId": e.commoditySkuId,
          "commoditySkuQuantity": e.commoditySkuNum,
        };
      }).toList();
      var response = await EcyRequestbasemanager()
          .post(EcyAPI.addCart.url, {"carts": carts});
      if (response != null) {
        var commonResponse =
            EcyApiCommonResponse.fromJson(response, (response) => json);
        if (commonResponse.code == 0 || commonResponse.code == 200) {
          EcyRouter.pushNoParams(context, EcyRouter.goodsCartHomePage);
        } else {
          EasyLoading.showToast(commonResponse.msg ?? "请稍后再试",
              duration: const Duration(seconds: 2));
        }
      }
    } catch (e) {
      EasyLoading.showToast("请稍后再试", duration: const Duration(seconds: 2));
    }
  }

  /// 取消订单
  _cancelOrder() async {
    bool? confirmFlag = await _showConfirmDialog("确定取消订单吗");
    if (confirmFlag == null || !confirmFlag) {
      return;
    }

    try {
      var response = await EcyRequestbasemanager()
          .get(EcyAPI.cancelOrder.url + (_order.orderCode ?? ""), {});
      if (response != null) {
        var commonResponse =
            EcyApiCommonResponse.fromJson(response, (response) => json);
        if (commonResponse.code == 0 || commonResponse.code == 200) {
          EasyLoading.showToast("已取消", duration: const Duration(seconds: 2));
          setState(() {
            requestData();
          });
          if(_onCallback != null) {
            _onCallback!("6");
          }
        } else {
          EasyLoading.showToast(commonResponse.msg ?? "请稍后再试",
              duration: const Duration(seconds: 2));
        }
      }
    } catch (e) {
      EasyLoading.showToast("请稍后再试", duration: const Duration(seconds: 2));
    }
  }

  /// 再次拼团
  _createGroupBuy() async {
    if (_orderItems.isEmpty) {
      EasyLoading.showToast("商品已失效", duration: const Duration(seconds: 2));
      return;
    }
    var goods = [];
    for (var item in _orderItems) {
      var num = item.commoditySkuNum ?? 1;
      var singlePrice =
          Decimal.parse((item.commoditySkuPrice ?? 0.00).toString());
      var totalPrice = Decimal.parse(num.toString()) * singlePrice;
      goods.add({
        "skuId": item.id,
        "price": double.parse(singlePrice.toString()),
        "salePrice": double.parse(singlePrice.toString()),
        "num": num,
        "totalPrice": double.parse(totalPrice.toString()),
        "imageUrl": item.commoditySkuImage,
        "skuName": item.commoditySkuName,
        "selectNum": num
      });
    }
    var msg = {"skuList": goods};
    EcyRouter.push(context, EcyRouter.orderConfirm, json.encode(msg));
  }

  /// 邀请好友
  _inviteFriends() async {
    var orderItem = _orderItems.isEmpty ? UserOrderItem() : _orderItems[0];
    String msg =
        '{"shareUrl":"${Constant.H5_BASE_URL}goodsDetailPage.html?goodsid=${orderItem.commodityId}&domain=${Uri.encodeComponent(Constant.API_BASE_URL)}&timestamp=${DateTime.now()}&noFlutter=1","shareTitle":"${orderItem.commodityName}","shareImageUrl":"${orderItem.commoditySkuImage}"}';
    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.transparent,
      isScrollControlled: true,
      builder: (context) => Container(
        height: MediaQuery.of(context).size.height * 0.3,
        decoration: const BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
        ),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(
              padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 24.h),
              decoration: BoxDecoration(
                border: Border(
                  bottom: BorderSide(
                    color: Colors.grey.withOpacity(0.1),
                  ),
                ),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Padding(
                    padding: const EdgeInsets.only(bottom: 10),
                    child: Text(
                      "邀请好友",
                      style: TextStyle(
                        fontFamily: "PingFang SC",
                        fontWeight: FontWeight.w600,
                        fontSize: 16.sp,
                        color: const Color(0xFF262626),
                      ),
                    ),
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    spacing: 16,
                    children: [
                      GestureDetector(
                        onTap: () {
                          EcyWxUtil.shareText(msg);
                        },
                        child: Column(
                          children: [
                            Image.asset('assets/images/wechat.png',
                                width: 50.w, height: 50.w),
                            Text(
                              "微信",
                              style: TextStyle(
                                fontFamily: "PingFang SC",
                                fontSize: 14.sp,
                                color: const Color(0xFF262626),
                              ),
                            )
                          ],
                        ),
                      ),
                      GestureDetector(
                        onTap: () {
                          EcyQQUtil.shareText(msg);
                        },
                        child: Column(
                          children: [
                            Image.asset('assets/images/qq.png',
                                width: 50.w, height: 50.w),
                            Text(
                              "QQ",
                              style: TextStyle(
                                fontFamily: "PingFang SC",
                                fontSize: 14.sp,
                                color: const Color(0xFF262626),
                              ),
                            )
                          ],
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 申请退款
  _applyRefund() async {
    try {
      var response = await EcyRequestbasemanager().post(EcyAPI.applyRefund.url,
          {"orderCode": _order.orderCode ?? "", "refundReason": "用户申请退款"});
      if (response != null) {
        var commonResponse =
            EcyApiCommonResponse.fromJson(response, (response) => json);
        if (commonResponse.code == 0 || commonResponse.code == 200) {
          EasyLoading.showToast("请等待商家处理~",
              duration: const Duration(seconds: 2));
          setState(() {
            requestData();
          });
          if(_onCallback != null) {
            _onCallback!("9");
          }
        } else {
          EasyLoading.showToast(commonResponse.msg ?? "请稍后再试",
              duration: const Duration(seconds: 2));
        }
      }
    } catch (e) {
      EasyLoading.showToast("请稍后再试", duration: const Duration(seconds: 2));
    }
  }

  Widget _buildBottomButtons() {
    List<Widget> buttons = [];
    bool groupBuyFlag = _order.orderType == "1" || _order.orderType == "4";
    switch (_order.orderStatus) {
      case 0: // 待付款
        buttons = [
          _buildButton("取消订单", false, _cancelOrder),
          SizedBox(width: 12.w),
          _buildButton("去支付", true, pay),
        ];
        break;
      case 2: // 拼团中
        buttons = [
          _buildButton("再次拼团", false, _createGroupBuy),
          SizedBox(width: 12.w),
          _buildButton("邀请好友", true, _inviteFriends),
        ];
        break;
      case 3: // 待发货
        buttons = [
          _buildButton("提醒发货", true, () {
            EasyLoading.showToast("已催促店家发货，还请耐心等待。",
                duration: const Duration(seconds: 2));
          }),
          if (_order.orderType == "0" ||
              _order.orderType == "2" ||
              _order.orderType == "3")
            SizedBox(width: 12.w),
          if (_order.orderType == "0" ||
              _order.orderType == "2" ||
              _order.orderType == "3")
            _buildButton("申请退款", false, _applyRefund),
        ];
        break;
      case 4: // 已发货-待收货
        buttons = [
          _buildButton("查看物流", false, _logistics),
          SizedBox(width: 12.w),
          _buildButton("确认收货", true, _sign),
        ];
        break;
      case 5: // 已完成
        buttons = [
          _buildButton(groupBuyFlag ? "再次拼团" : "加入购物车", false, () {
            if (groupBuyFlag) {
              _createGroupBuy();
            } else {
              _addCart();
            }
          }),
          SizedBox(width: 12.w),
          _buildButton("查看物流", false, _logistics),
          SizedBox(width: 12.w),
          _buildButton("评价", true, () {}),
        ];
        break;
      case 6: // 已取消
        buttons = [
          _buildButton(groupBuyFlag ? "再次拼团" : "加入购物车", false, () {
            if (groupBuyFlag) {
              _createGroupBuy();
            } else {
              _addCart();
            }
          }),
          // SizedBox(width: 12.w),
          // _buildButton("查看物流", false, _logistics),
        ];
        break;
      case 7: // 交易关闭
        buttons = [
          _buildButton(groupBuyFlag ? "再次拼团" : "加入购物车", false, () {
            if (groupBuyFlag) {
              _createGroupBuy();
            } else {
              _addCart();
            }
          }),
        ];
        break;
      case 8: // 拼团失败
        buttons = [
          _buildButton("再次拼团", true, _createGroupBuy),
        ];
        break;
      default:
        buttons = [];
    }

    return Container(
      color: Colors.white,
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
      child: Row(children: buttons),
    );
  }

  Container _getGroupBuyContainer(
      UserGroupBuyItemVo groupItem, List<UserGroupBuyItemVo> groupItems) {
    if (groupItem.groupBuyStatus == "0") {
      var waitingNum = groupItems.where((e) => e.userId == null).length;

      return Container(
        height: 32.w,
        margin: const EdgeInsets.only(
          top: 8,
        ),
        padding: const EdgeInsets.only(
          left: 8,
        ),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.all(Radius.circular(8.r)),
          color: const Color.fromARGB(15, 255, 83, 169),
        ),
        child: GestureDetector(
          behavior: HitTestBehavior.translucent,
          onTap: () {
            EcyRouter.push(
                context,
                '${Constant.H5_BASE_URL}groupBuying.html?groupBuyId=${groupItem.groupBuyId}&type=5&domain=${Constant.API_BASE_URL}&timestamp=${DateUtil.timestamp()}',
                {});
          },
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Row(
                children: [
                  Image.asset('assets/images/warning@2x.png', width: 17.w),
                  Text(' 待分享，还差$waitingNum位即可成团！',
                      style: TextStyle(
                        fontFamily: "PingFang SC",
                        fontWeight: FontWeight.w500,
                        fontSize: 14.sp,
                        color: const Color(0xFFEA4B9B),
                      )),
                ],
              ),
              const Padding(
                  padding: EdgeInsets.only(right: 8),
                  child: Image(
                      image: AssetImage('assets/images/rightArrow.png'),
                      width: 12)),
            ],
          ),
        ),
      );
    } else if (groupItem.groupBuyStatus == "1") {
      return Container(
        height: 32.w,
        margin: const EdgeInsets.only(
          top: 8,
        ),
        padding: const EdgeInsets.only(
          left: 8,
        ),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.all(Radius.circular(8.r)),
          color: const Color.fromARGB(15, 70, 219, 122),
        ),
        child: GestureDetector(
          behavior: HitTestBehavior.translucent,
          onTap: () {
            EcyRouter.push(
                context,
                '${Constant.H5_BASE_URL}groupBuying.html?groupBuyId=${groupItem.groupBuyId}&type=6&domain=${Constant.API_BASE_URL}&timestamp=${DateUtil.timestamp()}',
                {});
          },
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Row(
                children: [
                  Image.asset('assets/images/check-circle@2x.png', width: 17.w),
                  Text(" 拼团成功，盲盒正在快马加鞭赶来~",
                      style: TextStyle(
                        fontFamily: "PingFang SC",
                        fontWeight: FontWeight.w500,
                        fontSize: 14.sp,
                        color: const Color(0xFF46DB7A),
                      )),
                ],
              ),
              const Padding(
                  padding: EdgeInsets.only(right: 8),
                  child: Image(
                      image: AssetImage('assets/images/rightArrow.png'),
                      width: 12))
            ],
          ),
        ),
      );
    } else if (groupItem.groupBuyStatus == "2") {
      return Container(
        height: 32.w,
        margin: const EdgeInsets.only(
          top: 8,
        ),
        padding: const EdgeInsets.only(
          left: 8,
        ),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.all(Radius.circular(8.r)),
          color: const Color.fromARGB(15, 245, 95, 78),
        ),
        child: GestureDetector(
          behavior: HitTestBehavior.translucent,
          onTap: () {
            EcyRouter.push(
                context,
                '${Constant.H5_BASE_URL}groupBuying.html?groupBuyId=${groupItem.groupBuyId}&type=7&domain=${Constant.API_BASE_URL}&timestamp=${DateUtil.timestamp()}',
                {});
          },
          child: Row(
            children: [
              Row(
                children: [
                  Image.asset('assets/images/x-circle@2x.png', width: 17.w),
                  Text(" 拼团失败，多分享可以增加成功几率哦~",
                      style: TextStyle(
                        fontFamily: "PingFang SC",
                        fontWeight: FontWeight.w500,
                        fontSize: 14.sp,
                        color: const Color(0xFFF55F4E),
                      )),
                ],
              ),
              const Padding(
                  padding: EdgeInsets.only(right: 8),
                  child: Image(
                      image: AssetImage('assets/images/rightArrow.png'),
                      width: 12)),
            ],
          ),
        ),
      );
    }
    return Container();
  }

  // 弹出对话框
  Future<bool?> _showConfirmDialog(String content) {
    return showDialog<bool>(
      context: context,
      builder: (context) {
        return AlertDialog(
          // title: const Text(''),
          contentPadding: const EdgeInsets.all(0),
          backgroundColor: Colors.white,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(8.0),
          ),
          content: SizedBox(
            height: 130,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Padding(
                  padding: const EdgeInsets.only(top: 20, bottom: 30),
                  child: Text(
                    content,
                    style: const TextStyle(fontSize: 18),
                  ),
                ),
                const Divider(height: 0, color: Color(0XFFdcdcdc)),
                SizedBox(
                  height: 50,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                      Expanded(
                        flex: 1,
                        child: DecoratedBox(
                          decoration: const BoxDecoration(
                              border: Border(
                            right: BorderSide(
                              width: 1.0,
                              color: Color(0XFFdcdcdc),
                            ),
                          )),
                          child: TextButton(
                            style: const ButtonStyle(
                              alignment: Alignment.center,
                            ),
                            child: const Text(
                              '我再想想',
                              style:
                                  TextStyle(fontSize: 18, color: Colors.black),
                            ),
                            onPressed: () =>
                                Navigator.of(context).pop(), // 关闭对话框
                          ),
                        ),
                      ),
                      Expanded(
                        flex: 1,
                        child: TextButton(
                          child: const Text(
                            '确定',
                            style: TextStyle(
                                fontSize: 18, color: Color(0xFFEA4B9B)),
                          ),
                          onPressed: () {
                            //关闭对话框并返回true
                            Navigator.of(context).pop(true);
                          },
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
          actionsAlignment: MainAxisAlignment.spaceAround,
          actionsPadding: const EdgeInsets.all(0),
        );
      },
    );
  }
}
